package com.leetcode.basic.synchronize.ReentrantLock;

import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by haicheng.lhc on 17/05/2017.
 *
 * @author haicheng.lhc
 * @date 2017/05/17
 */
public class ReentrantLockDemo extends Thread {

	public static int i = 0;

	// 验证ReentrantLock同步效果
	@Test
	public void test() throws InterruptedException {
		Thread test1 = new TH("thread1");
		Thread test2 = new TH("thread2");

		test1.start();
		test2.start();
		test1.join();
		test2.join();

		// 结果是20000
		Assert.assertEquals(20000, i);
	}

	class TH extends Thread {

		public ReentrantLock lock = new ReentrantLock();


		public TH(String name) {
			super.setName(name);
		}

		@Override
		public void run() {
			for (int j = 0; j < 10000; j++) {
				lock.lock();
				try {
					if (i > 19900) {
						System.out.println(this.getName() + " " + i);
					}
					i++;
				} finally {
					lock.unlock();
				}
			}
		}
	}
}